﻿using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;

using Zivsoft.Utils;
using Zivsoft.Log;
/**************************
 * 
 * 
 * 
 **************************/
namespace Zivsoft.Business.Spider
{

    /// <summary>
    /// Spider Utility
    /// </summary>
    class Search:ISearch
    {
        private string _url;
        private string _outPath;
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        public Search(string url) 
        {
            _url = url;          
        }


        /// <summary>
        /// Get inner html content from url
        /// </summary>
        /// <param name="url">url</param>
        /// <returns>return the html source</returns>
        public  string GetHtmlSourceText()
        {
            Stream s = null;
            var uri = new Uri(_url);
            var req = (HttpWebRequest)WebRequest.Create(uri);
            WebResponse res = null;
            try
            {
                res = req.GetResponse();
            }
            catch (Exception e)
            {
                Logger.LogError(e.Message);
                return "";
            }
            s = res.GetResponseStream();
            var sr = new StreamReader(s);
            var strHtml = sr.ReadToEnd();
            return strHtml;
        }

        /// <summary>
        /// Match the items from the text with the rex
        /// </summary>
        /// <param name="text">html source text</param>
        /// <param name="rex">rex patern</param>
        /// <returns>return the arraylist</returns>
        public ArrayList MachItems(string text,string rex)
        {
            if (string.IsNullOrEmpty(text))
            {
                return new ArrayList();
            }
            var str = text;
            var al = new ArrayList();
            var rgx = new Regex(rex, RegexOptions.Singleline);
            var cols = rgx.Matches(str);
            foreach (Match m in cols)
            {
                var v = m.Groups[0].Value;
                Logger.LogInfo(v);
                al.Add(v);
            }
            return al;
        }

        /// <summary>
        /// Save pic from url that has the jpg key word
        /// </summary>
        public void SavePicFromUrl(string imgUrl, string folderName)
        {
            _outPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folderName);
            if (Directory.Exists(_outPath))
            {
                Logger.LogDebug("folder has already existed: {0}", _outPath);
            }
            else
            {
                try
                {
                    Directory.CreateDirectory(_outPath);
                }
                catch
                {
                    _outPath = AppDomain.CurrentDomain.BaseDirectory;
                }
            }
            int height = 400;
            int width = 300;
            var filename = FileUtils.getFileName(imgUrl);            
            var uri = new Uri(imgUrl);
            var req = WebRequest.Create(uri);
            WebResponse res = null;
            try
            {
                res = req.GetResponse();
            }
            catch(Exception e)
            {
                Logger.LogError("error:" + e.Message);
                return;
            }

            var s = res.GetResponseStream();
            try
            {
                var img = Image.FromStream(s);
                if (img.Width*img.Height<height * width) return;
                if(File.Exists(Path.Combine(_outPath,filename))){
                    var existImg=Image.FromFile(Path.Combine(_outPath,filename));
                    if (existImg.Flags==img.Flags&&existImg.Size == img.Size)
                    {
                        return;
                    }
                }
                var save = Path.Combine(_outPath, RandomName.GetUniqueNameByStoreFile(_outPath, filename));
                img.Save(save);
                Logger.LogInfo("{0} has been saved successfully", save);

            }
            catch(Exception e)
            {
                Logger.LogError("Error:{0}",e);
            }
        }
    }
}